package com.example.demo.interceptor;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.util.JWTUtil;
import com.example.demo.util.MyException;
import com.example.demo.util.ResultCode;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = StringUtils.isBlank(request.getHeader("token")) ? request.getParameter("token") : request.getHeader("token");
        if (StringUtils.isNotBlank(token)) {
            Claims claims = JWTUtil.checkToken(token);
            if (claims == null) {
                throw new MyException(ResultCode.NOT_LOGIN);
            }
        } else {
            throw new MyException(ResultCode.NOT_LOGIN);
        }
        return true;
    }
}
